﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OvenParameterForm.Util
{
    internal class DebouncedRisingEdgeDetector
    {
        bool _previousState;
        DateTime _lastTriggerTimer = DateTime.MinValue;
        readonly int _debounceMs;
        readonly object _lock = new object();
        public DebouncedRisingEdgeDetector(int debounceMilliseconds, bool initialState = false)
        {
            _debounceMs = debounceMilliseconds > 0 ? debounceMilliseconds : 10;
            _previousState = initialState;
        }
        public bool CheckForRisingEdge(bool currentState)
        {
            lock (_lock)
            {
                bool edgeDetecked = false;
                bool potentialEdge = !_previousState && currentState;
                if (potentialEdge)
                {
                    TimeSpan elapsed = DateTime.UtcNow - _lastTriggerTimer;
                    if (elapsed.TotalMilliseconds > _debounceMs)
                    {
                        edgeDetecked = true;
                        _lastTriggerTimer = DateTime.UtcNow;
                    }
                }
                _previousState = currentState;
                return edgeDetecked;
            }
        }

        public void Reset(bool initialState = false)
        {
            lock (_lock)
            {
                _previousState = false;
                _lastTriggerTimer = DateTime.MinValue;
            }
        }
    }
}
